package org.demo.warehouse.common.utils;

/***
 * 调用用户中心，用作读写用户信息数据
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.demo.warehouse.common.exception.BusinessException;
import org.demo.warehouse.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.Map;

/**
 * @author ZGC
 * @date 2019-10-24
 **/
@Slf4j
public class RemoteUtil {

    private static RestTemplate restTemplate;

    private static ISysConfigService configService;

    static {
        restTemplate = SpringUtil.getBean(RestTemplate.class);
        configService = SpringUtil.getBean(ISysConfigService.class);
    }

    public static void judgeResEntity(ResponseEntity<String> response) {
        String responseMessage = response.getBody();
        if (response.getStatusCode().equals(HttpStatus.OK)) {
            log.info("请求成功，返回信息：{}", responseMessage);
        } else {
            log.error("请求失败，状态码：{}，返回信息：{}", response.getStatusCode().value(), responseMessage);
            throw new BusinessException("请求失败");
        }
    }

    public static String sendGetToUAA(String methodUrl, String param) {
        methodUrl = configService.getAuthenticationUrl() + methodUrl;
        log.info("发送get请求至用户中心，地址：{}?data={}", methodUrl, param);
        ResponseEntity<String> response = restTemplate.getForEntity(methodUrl + "?data={param}", String.class, param);
        String result = response.getBody();
        judgeResEntity(response);
        return result;
    }

    public static JSONObject sendPostToUAA(String token, String methodUrl, Map<String, Object> paramMap) {
        String url = configService.getAuthenticationUrl() + methodUrl;
        // header填充
        LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.put("Access-Token", Collections.singletonList(token));
        // body填充
        HttpEntity<String> request = new HttpEntity<String>(null, headers);
        JSONObject responseEntity;
        if (paramMap != null) {
            String params = JSON.toJSONString(paramMap);
            log.info("发送post请求至用户中心，地址：{}?data={}", url, params);
            url += "?data={params}";
            responseEntity = restTemplate.postForObject(url, request, JSONObject.class, params);
        } else {
            log.info("发送post请求至用户中心，地址：{}", url);
            responseEntity = restTemplate.postForObject(url, request, JSONObject.class);
        }
        if (!"true".equals(responseEntity.getString("success"))) {
            throw new BusinessException(responseEntity.getString("info"));
        }
        return responseEntity;
    }
}
